from flask import Blueprint, jsonify, request
from app.models.Skillc2 import ClubNews
from app import db
from flask_jwt_extended import jwt_required, get_jwt_identity
from datetime import datetime

club_bp = Blueprint('club', __name__)

@club_bp.route('/clubs/news', methods=['GET'])
def get_club_news_list():
    """获取社团新闻列表"""
    try:
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int)
        
        news_list = ClubNews.query.order_by(ClubNews.CreateTime.desc()).paginate(page=page, per_page=per_page)
        
        return jsonify({
            'status': 'success',
            'data': {
                'items': [news.to_list_dict() for news in news_list.items],
                'total': news_list.total,
                'pages': news_list.pages,
                'current_page': page,
                'has_next': news_list.has_next,
                'has_prev': news_list.has_prev
            }
        })
    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@club_bp.route('/clubs/news/<int:news_id>', methods=['GET'])
def get_club_news(news_id):
    """获取社团新闻详情"""
    try:
        news = ClubNews.query.get_or_404(news_id)
        
        return jsonify({
            'status': 'success',
            'data': news.to_dict()
        })
    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@club_bp.route('/clubs/news', methods=['POST'])
@jwt_required()
def create_club_news():
    """创建社团新闻"""
    try:
        data = request.get_json()
        
        # 验证必要字段
        required_fields = ['title']
        if not all(field in data for field in required_fields):
            return jsonify({
                'status': 'error',
                'message': '缺少必要字段'
            }), 400
        
        # 处理创社时间
        founding_time = None
        if 'founding_time' in data and data['founding_time']:
            try:
                founding_time = datetime.strptime(data['founding_time'], '%Y-%m-%d %H:%M:%S')
            except ValueError:
                return jsonify({
                    'status': 'error',
                    'message': '创社时间格式错误，应为YYYY-MM-DD HH:MM:SS'
                }), 400
        
        news = ClubNews(
            Title=data['title'],
            CoverImage=data.get('cover_image'),
            FoundingTime=founding_time,
            Introduction=data.get('introduction'),
            ClubBrief=data.get('club_brief'),
            LeaderPhoto=data.get('leader_photo'),
            MemberCount=data.get('member_count', 0),
            ActivityTime=data.get('activity_time'),
            ActivityLocation=data.get('activity_location'),
            ClubRules=data.get('club_rules')
        )
        
        db.session.add(news)
        db.session.commit()
        
        return jsonify({
            'status': 'success',
            'message': '社团新闻创建成功',
            'data': news.to_dict()
        }), 201
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@club_bp.route('/clubs/news/<int:news_id>', methods=['PUT'])
@jwt_required()
def update_club_news(news_id):
    """更新社团新闻"""
    try:
        news = ClubNews.query.get_or_404(news_id)
        data = request.get_json()
        
        # 更新字段
        if 'title' in data:
            news.Title = data['title']
        if 'cover_image' in data:
            news.CoverImage = data['cover_image']
        if 'founding_time' in data and data['founding_time']:
            try:
                news.FoundingTime = datetime.strptime(data['founding_time'], '%Y-%m-%d %H:%M:%S')
            except ValueError:
                return jsonify({
                    'status': 'error',
                    'message': '创社时间格式错误，应为YYYY-MM-DD HH:MM:SS'
                }), 400
        if 'introduction' in data:
            news.Introduction = data['introduction']
        if 'club_brief' in data:
            news.ClubBrief = data['club_brief']
        if 'leader_photo' in data:
            news.LeaderPhoto = data['leader_photo']
        if 'member_count' in data:
            news.MemberCount = data['member_count']
        if 'activity_time' in data:
            news.ActivityTime = data['activity_time']
        if 'activity_location' in data:
            news.ActivityLocation = data['activity_location']
        if 'club_rules' in data:
            news.ClubRules = data['club_rules']
        
        news.UpdateTime = datetime.now()
        db.session.commit()
        
        return jsonify({
            'status': 'success',
            'message': '社团新闻更新成功',
            'data': news.to_dict()
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@club_bp.route('/clubs/news/<int:news_id>', methods=['DELETE'])
@jwt_required()
def delete_club_news(news_id):
    """删除社团新闻"""
    try:
        news = ClubNews.query.get_or_404(news_id)
        
        db.session.delete(news)
        db.session.commit()
        
        return jsonify({
            'status': 'success',
            'message': '社团新闻删除成功'
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500 